#!/usr/bin/env bash
set -euo pipefail

##? release

export NAVI_HOME="$(cd "$(dirname "$0")/.." && pwd)"
source "${NAVI_HOME}/scripts/install"

is_windows() {
   local -r target="$1"
   echo "$target" | grep -q "windows"
}

get_env_target() {
   eval $(rustc --print cfg | grep target)
   local r raw="${target_arch}-${target_vendor}-${target_os}-${target_env}"
   log::note "env target raw: $raw"
   if echo "$raw" | grep -q "x86_64-apple-macos"; then
      echo "x86_64-apple-darwin"
   else
      echo "$raw"
   fi
}

_tap() {
   log::note "$@"
   "$@"
}

release() {
   local -r env_target="$(get_env_target)"
   log::note "env target: $env_target"

   local -r cross_target="${1:-"$env_target"}"
   log::note "desired target: $cross_target"

   TAR_DIR="${NAVI_HOME}/target/tar"
   local use_zip=false
   local cross=true

   if [[ $cross_target == $env_target ]]; then
      cross=false
   fi

   cd "$NAVI_HOME"

   rm -rf "${NAVI_HOME}/target" 2> /dev/null || true

   if $cross; then
      cargo install cross 2> /dev/null || true
      _tap cross build --release --locked --target "$cross_target"
      local -r bin_folder="${cross_target}/release"
   else
      _tap cargo build --release --locked
      local -r bin_folder="release"
   fi

   _ls "${bin_folder}"

   if is_windows "$cross_target"; then
      local -r exe_ext=".exe"
      use_zip=true
   else
      local -r exe_ext=""
   fi

   bin_path="${NAVI_HOME}/target/${bin_folder}/navi${exe_ext}"

   chmod +x "$bin_path"
   mkdir -p "$TAR_DIR" 2> /dev/null || true

   cp "$bin_path" "$TAR_DIR"

   cd "$TAR_DIR"

   if $use_zip; then
      zip -r navi.zip *
      echo ::set-output name=EXTENSION::zip
   else
      tar -czf navi.tar.gz *
      echo ::set-output name=EXTENSION::tar.gz
   fi

   _ls "${bin_path}"
   _ls "${TAR_DIR}"
}

_ls() {
   log::note "contents from $@:"
   ls -la "$@" || true
}

release "$@"
